function convertToDate(date){
    var parts = date.split("/");
    return new Date(parts[2], parts[1] - 1, parts[0]);
} 

$.getServices = function() {

    $('#progressPagos').modal({ backdrop: 'static' });

    $("#tblServicios tbody").remove();

    $.ajax({
      url:'controller/controller.php',
      type:'POST',
      data: { option: 'getServices' }
    }).success(function(data){
        var json = eval('(' + data + ')');
        $.each(json, function(i, item) {     

            if (item.status === 'A')
                estado = "checked";
            else
                estado = "";

            row = '<tr id="ser_trServices_' + item.service_id + '"> \
                       <td id="name" style="vertical-align:middle;" class="text-left">'  + item.name              + '</td> \
                       <td id="start_date_active" style="vertical-align:middle;" class="text-right">' + item.start_date_active + '</td> \
                       <td id="end_date_active" style="vertical-align:middle;" class="text-right">' + item.end_date_active   + '</td> \
                       <td style="vertical-align:middle;" class="text-center"><input id="status" type="checkbox" disabled ' + estado + ' ></td> \
                       <td style="vertical-align:middle;" class="text-center"> \
                           <a serviceID="' + item.service_id + '" serviceName="' + item.name + '" id="ser_btnEdit" class="btn btn-warning" href="#"><i class="icon-edit icon-white"></i></a> \
                           <a serviceID="' + item.service_id + '" serviceName="' + item.name + '" id="ser_btnDelete" class="btn btn-danger" href="#"><i class="icon-trash icon-white"></i></a> \
                       </td> \
                   </tr>';

            $('#tblServicios').append(row);
        });
    })
    .error (function (request, status, error) {
        alert(request.responseText); })
    .fail(function(request, error)  {alert("Error obteniendo servicios: " + error);});

    $('#progressPagos').modal('hide');
    
};
    
$.infoService = function(id) {
    $.ajax({
        type: 'post',
        url: 'controller/controller.php',
        data: {option: 'getInfoService', serviceID: id},
        success: function(data) {
            var json = eval('(' + data + ')');
            $.each(json, function(key, val) {
                
                if (key != "status")
                    $('#ser_' + key + '_add').val(val);
                else
                    if ( val == 'A' )
                        $('#ser_status_add').prop('checked', true);
                    else
                        $('#ser_status_add').prop('checked', false);
                
            });
        }
    });
};

$.insertService = function($data) {
    
    $data.push({
        name: 'option',
        value: 'insertService'
    });
    
    $.ajax({
        type: 'post',
        url: 'controller/controller.php',
        data: $.param($data),
        success: function(data) {
            var json = eval('(' + data + ')');
            
            if(typeof json.success == 'undefined'){
                
                var estado = '';

                if ($('#ser_status_add').prop('checked'))
                    estado = 'checked';
                
                row = '<tr id="ser_trServices_' + json.last_id + '"> \
                         <td id="name" style="vertical-align:middle;" class="text-left">'  + $('#ser_name_add').val() + '</td> \
                         <td id="start_date_active" style="vertical-align:middle;" class="text-right">' + $('#ser_start_date_active_add').val() + '</td> \
                         <td id="end_date_active" style="vertical-align:middle;" class="text-right">' + $('#ser_end_date_active_add').val()   + '</td> \
                         <td style="vertical-align:middle;" class="text-center"><input id="status" type="checkbox" disabled ' + estado + ' ></td> \
                         <td style="vertical-align:middle;" class="text-center"> \
                             <a serviceID="' + json.last_id + '" serviceName="' + $('#ser_name_add').val() + '" id="ser_btnEdit" class="btn btn-warning" href="#"><i class="icon-edit icon-white"></i></a> \
                             <a serviceID="' + json.last_id + '" serviceName="' + $('#ser_name_add').val()+ '" id="ser_btnDelete" class="btn btn-danger" href="#"><i class="icon-trash icon-white"></i></a> \
                         </td> \
                     </tr>';
                
                if (json.afterServiceID)
                    $('#ser_trServices_' + json.afterServiceID).after(row);
                else
                    $('#tblServicios').prepend(row);
                
                $('#ser_name_add').val("");
                $('#ser_start_date_active_add').val("");
                $('#ser_end_date_active_add').val("");
                $('#DATA').data('option', '');
                $('#ser_status_add').prop('checked', false);
                $('#modal-editadd-service').modal('hide');
                $('#modal-confirmation-delete').modal('hide');    
            }
            else
                alert("Error: " + json.message + "sql: " + json.sql);

        }
    });     
};

$.updateService = function($data) {
    
    $data.push({
        name: 'serviceID',
        value: $('#DATA').data('id')
    });
    
    $data.push({
        name: 'option',
        value: 'updateService'
    });
    
    $.ajax({
        type: 'post',
        url: 'controller/controller.php',
        data: $.param($data),
        success: function(data) {
            var json = eval('(' + data + ')');
            
            if (json.success === 1) {

                $.updateTrService($data);
                $('#ser_name_add').val("");
                $('#ser_start_date_active_add').val("");
                $('#ser_end_date_active_add').val("");
                $('#DATA').data('option', '');
                $('#ser_status_add').prop('checked', false);
                $('#modal-editadd-service').modal('hide');
                $('#modal-confirmation-delete').modal('hide');

            } else
                alert("ERROR!!");
        }
    }); 
};

$.deleteService = function(serviceID) {
    $.ajax({
          url:'controller/controller.php',
          type:'POST',
          data: { option: 'deleteService', serviceID: serviceID }
      }).success(function(data){
            var json = eval('(' + data + ')');
            if (json.success === 1) {

                $('#ser_trServices_' + serviceID).remove();
                $('#modal-confirmation-delete').modal('hide');

            } else
                alert("ERROR!!");
    });
};

$.updateTrService = function($data) {
    
    $.each($data, function(i, item) { 
        if ( item["name"] == "serviceID" )
            serviceID = item["value"];
    });
    
    $('#ser_trServices_' + serviceID + ' td input#status').prop('checked', false);
    
    $.each($data, function(i, item) { 
        
        switch (item["name"]) {
            case "name":
                $('#ser_trServices_' + serviceID + ' td#name').html(item["value"]);
                break;
            case "start_date_active":
                $('#ser_trServices_' + serviceID + ' td#start_date_active').html(item["value"]);
                break;
            case "end_date_active":
                $('#ser_trServices_' + serviceID + ' td#end_date_active').html(item["value"]);
                break;
            case "status":
                if (item["value"] == "on")
                    $('#ser_trServices_' + serviceID + ' td input#status').prop("checked", true);
                break;
         }
         
    });
    
};

$(document).ready(function(){

    $.getServices();
    $(document).off('click', '#ser_del_service').on('click', '#ser_del_service', function() {    
        var serviceID = $('#ser_del_service').attr('delServiceID');
        $.deleteService(serviceID);
    });
    
    $(document).off('click', '#ser_btnDelete').on('click', '#ser_btnDelete', function() {
        
        var serviceName = $(this).attr('serviceName');
        var serviceID = $(this).attr('serviceID');

        $('#ser_msg_str').text('').text('Desea borrar el servicio de ' + serviceName + '?');
        $('#ser_del_service').attr('delServiceID', serviceID);
        $('#modal-confirmation-delete').modal({ backdrop: 'static' });  
    });    
    
    $(document).off('click', '#ser_btnEdit').on('click', '#ser_btnEdit', function() {
        $('#DATA').data('id', $(this).attr('serviceID'));
        $('#DATA').data('option', 'update');
        $('#modal-editadd-service #titulo').text('').text('Actualizar Servicio');
        $.infoService($(this).attr('serviceID'));
        $("#ui-datepicker-div").css("z-index", "9999");
        $('#modal-editadd-service').modal('show');
    });
    
    $(document).off('click', '#ser_btn_cancelar').on('click', '#ser_btn_cancelar', function() {    
        $('#ser_name_add').val("");
        $('#ser_start_date_active_add').val("");
        $('#ser_end_date_active_add').val("");
        $('#DATA').data('option', '');
        $('#ser_status_add').prop('checked', false);
        $('#modal-editadd-service').modal('hide');
    });
    
    /*
    $(document).off('click', '#ser_btn_capo').on('click', '#ser_btn_capo', function() {
       $('#form-add').data('bootstrapValidator').validate(); 
       
       //$('#form-add').bootstrapValidator('isValid');
       var bootstrapValidator = $('#form-add').data('bootstrapValidator');
       
       alert(bootstrapValidator.isValid());
    });
    */
    
    $(document).off('click', '#ser_btn_aceptar').on('click', '#ser_btn_aceptar', function() {
   
        //
        // Ejecuto la validación primero y luego consulto si falló o no
        //
        $('#form-add').data('bootstrapValidator').validate(); 
        var bootstrapValidator = $('#form-add').data('bootstrapValidator');
        
        if ( bootstrapValidator.isValid() )
            if ($('#DATA').data('option') === 'insert')
                $.insertService($('#form-add').serializeArray());
            else
                if ($('#DATA').data('option') === 'update')
                    $.updateService($('#form-add').serializeArray());
    });   
    
    // ---------------------
    // Date Picker
    // ---------------------


    $('#ser_start_date_active_add, #ser_end_date_active_add').datepicker({ format: 'dd/mm/yyyy'});
    
    $('#ser_start_date_active_add, #ser_end_date_active_add').datepicker().on('show', function(ev){
        $(this).datepicker({
            setValue: $(this).val()
        });
    });
    
    $('#ser_start_date_active_add').datepicker().on('changeDate', function(ev){
        
        var dateFrom = $('#ser_start_date_active_add').val();
        var dateTo = $('#ser_end_date_active_add').val();
        
        if ( dateTo !== "")
            if ( convertToDate(dateFrom) > convertToDate(dateTo) ){
                alert("La Fecha Desde no puede ser mayor que la Fecha Hasta!");
                $('#ser_start_date_active_add').val("");
            }
        
    });
    
    $('#ser_end_date_active_add').datepicker().on('changeDate', function(ev){
       
        var dateFrom = $('#ser_start_date_active_add').val();
        var dateTo = $('#ser_end_date_active_add').val();
        
        if ( dateTo !== "")
            if ( convertToDate(dateTo) < convertToDate(dateFrom) ){
                alert("La Fecha Hasta no puede ser menor que la Fecha Desde!");
                $('#ser_end_date_active_add').val("");
            }        
        
    });    
    
    $(document).off('click', '#ser_btnAdd').on('click', '#ser_btnAdd', function() {
        $('#ser_name_add').val("");
        $('#ser_start_date_active_add').val("");
        $('#ser_end_date_active_add').val("");
        $('#DATA').data('option', '');
        $('#ser_status_add').prop('checked', false);
        $('#modal-editadd-service').modal('hide');
        
        $('#DATA').data('option', 'insert');
        $('#DATA').data('id', '');
        $('#modal-editadd-service #titulo').text('').text('Agregar Servicio');        
        $("#ui-datepicker-div").css("z-index", "9999");

        var bootstrapValidator = $('#form-add').data('bootstrapValidator');
        bootstrapValidator.resetForm(true);
        
        $('#modal-editadd-service').modal('show');
    });
    
    $('#form-add').bootstrapValidator({
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            name: {
                validators: {
                    notEmpty: {
                        message: 'El Nombre del servicio es obligatorio'
                    }
                }
            },
            start_date_active: {
                validators: {
                    notEmpty: {
                        message: 'La Fecha Desde del Servicio es obligatoria'
                    },
                    date: {
                        message: 'Formato de fecha incorrecta (dd/mm/yyyy)'
                    }
                }
            },
            end_date_active: {
                validators: {
                    date: {
                        message: 'Formato de fecha incorrecta (dd/mm/yyyy)'
                    }
                }
            }            
        }
    });

});